#!/bin/sh

generate_rand_mac() {
    local hex_raw ouipart euipart full_mac byte1 byte1_hex
    local oldIFS="$IFS" # Save the original field separator
    while :; do
        # Generate raw data (compatible with BusyBox)
        hex_raw=$(head -c6 /dev/urandom | hexdump -v -e '/1 "%02x "') || continue

        # Split byte data
        IFS=' '         # Set space as the delimiter
        set -- $hex_raw # Store in positional parameters
        IFS="$oldIFS"   # Restore the original field separator
        [ $# -ne 6 ] && continue

        # Process the first byte
        byte1=$((0x$1 & 0xFC)) # Force unicast + global address
        byte1_hex="$(printf "%02x" "$byte1")"

        # Construct MAC components
        ouipart="$byte1_hex:$2:$3"
        euipart="$4:$5:$6"
        full_mac="$byte1_hex:$2:$3:$4:$5:$6"

        # OUI blacklist check
        case "$ouipart" in
        "00:00:00" | \
            "ff:ff:ff" | \
            "00:00:0c" | \
            "01:00:5e" | \
            "33:33:"*)
            continue
            ;;
        esac

        # EUI blacklist check
        case "$euipart" in
        "00:00:00" | \
            "ff:ff:f"*)
            continue
            ;;
        esac

        # Final format validation
        echo "$full_mac" | grep -qE '^([0-9a-f]{2}:){5}[0-9a-f]{2}$' || continue
        break
    done

    echo "$full_mac"
}

if [ "$ACTION" = "ifdown" ]; then
	echo "$DEVICE" | grep -q "^pppoe-vwan[[:digit:]]\+$" &&
		pppconnectcheck &
elif [ "$ACTION" = "ifup" ]; then
	ifname=$(uci -q get network.wan.ifname)
	[ "$(uci -q get syncdial.config.enabled)" -eq 1 ] &&
		[ "$DEVICE" = "$ifname" ] && {
		wannum=$(uci -q get syncdial.config.wannum)
		for i in $(seq 1 "$wannum"); do
			[ -d "/sys/class/net/macvlan$i" ] || {
				ip link add link "$ifname" name "macvlan$i" type macvlan
				ifconfig "macvlan$i" hw ether "$(generate_rand_mac)"
				ifconfig "macvlan$i" up
			}
		done
	}
fi
